/**********************************************************************
 * 
 * Name: ClockInOutREST
 * Object: ClockInOutHistory__c
 * Purpose: 导出上下班打卡记录到OA
 * Requirement:
 * Author: kittylau (382376269@qq.com)
 * Create Date: 2017-01-17
 * Modify History: 
 * 
 * Url: /services/apexrest/CRM/clockInOutREST
 * 接收的Json数据格式:
   {
        "data":{"ts":"最后更新时间"}
   }
  返回的Json数据格式：
  {
    "result":"0 OR 1 , 1表示成功，0表示失败", 
    "result_msg":"成功为取得的数据条数，失败时为失败原因信息",
    "data":[{
        "Id":"记录Id",
        "SerialNumber":"打卡流水号",
        "UserName":"员工名称",
        "UserCode":"员工编号",
        "LoginName":"员工登录名称",
        "MobilePhone":"手机",
        "Department":"部门",
        "Title":"职务",
        "Email":"电子邮箱",
        "ClockInTime":"上班打卡时间",
        "ClockInLocation":"上班打卡定位",
        "InLocation":"上班详细地址",
        "ClockOutTime":"下班打卡时间",
        "ClockOutLocation":"下班打卡定位",
        "OutLocation":"下班详细地址",
        "WorkHour":"工作时长(小时)",
        "ts":"最后更新时间"
    },{...}]
  }
*************************************************************************/
@RestResource(urlMapping='/CRM/clockInOutREST/*')
global class ClockInOutREST {
    @HttpPost
    global static RestReturnMessage getClockInOutREST(Map<String,String> data) {
        RestReturnMessage msg = null;
        if(data != null && data.containsKey('ts')){
            try{
                Datetime dt = Datetime.valueOf(data.get('ts'));
                try{
                    msg = getClockInOut(dt);
                }
                catch(Exception ex){
                    System.debug('*** 错误信息: ' + ex.getMessage() + ' - ' + ex.getStackTraceString());
                    msg = Utils.getRestReturnMessage(false,ex.getMessage()+ ' - ' + ex.getStackTraceString());
                }
            }catch(Exception ex){
                System.debug('*** 错误信息: ' + ex.getMessage() + ' - ' + ex.getStackTraceString());
                msg = Utils.getRestReturnMessage(false,'错误的ts参数值,需要日期时间格式(yyyy-MM-dd HH:mm:ss)');
            }
        }else{
            System.debug('*** 错误信息: 参数错误');
            msg = Utils.getRestReturnMessage(false,'参数错误');
        }
        return msg;
    }

    /*
        描述：以上次读取时的最大时间为基准，读取最新上下班打卡数据
        参数：ts - 上次读取时的最大时间
    */
    global static RestReturnMessage getClockInOut (Datetime ts) {
        Datetime maxTs = Datetime.valueOf(Utils.MIN_DATE_TIME);
        System.debug(LoggingLevel.INFO, '*** ESB最后保存的更新时间: ' + ts);

        //最新的打卡数据
        // List<ClockInOutHistory__c> roList = [SELECT Id,Name,WorkHour__c,ClockInTime__c,ClockInLocation__c,
        // 			 InLocation__c,ClockOutTime__c,ClockOutLocation__c,OutLocation__c,
        // 			 User__r.Name,User__r.Alias,User__r.CommunityNickname,User__r.Username,
        // 			 User__r.MobilePhone,User__r.Department,User__r.Email,User__r.Title,User__r.EmployeeNumber  
        //         FROM ClockInOutHistory__c  
        //         WHERE ClockOutTime__c != null AND ClockOutTime__c >= :ts
        //         LIMIT 1000];
        //保存要返回给调用者的数据集合
        Map<String, List<Map<String,String>>> datasMap = new Map<String, List<Map<String,String>>>();
        List<Map<String,String>> datas = new List<Map<String,String>>();
        Integer i = 0;
        Integer cnt = 0;
        for(ClockInOutHistory__c ro : [SELECT Id,Name,WorkHour__c,ClockInTime__c,ClockInLocation__c,
                     InLocation__c,ClockOutTime__c,ClockOutLocation__c,OutLocation__c,
                     User__r.Name,User__r.Alias,User__r.CommunityNickname,User__r.Username,
                     User__r.MobilePhone,User__r.Department,User__r.Email,User__r.Title,User__r.EmployeeNumber  
                FROM ClockInOutHistory__c  
                WHERE ClockInTime__c != null AND ClockInTime__c >= :ts]){
            if(ro.ClockInTime__c > maxTs){
                maxTs = ro.ClockInTime__c;
            }
            Map<String,String> data = new Map<String,String>();
            String name = ro.User__r.Name;
            if(name !=null){
            	name = name.split(' ',-1)[0];
                if(name.length() >10)name=name.subString(0,10);
            }
            //CRM数据
            data.put('Id', ro.Id);//记录id
            data.put('SerialNumber', ro.Name);//打卡流水号
            data.put('UserName', name);//员工姓名
            data.put('UserCode', ro.User__r.EmployeeNumber);//员工编号
            data.put('LoginName', ro.User__r.Username);//员工登录名称
            data.put('MobilePhone', ro.User__r.MobilePhone);//员工手机
            data.put('Department', ro.User__r.Department);//员工部门
            data.put('Title', ro.User__r.Title);//员工职务
            data.put('Email', ro.User__r.Email);//员工Email
            data.put('ClockInTime', ro.ClockInTime__c.format(Utils.DATETIME_FORMAT_STR));//上班打卡时间
            data.put('ClockInLocation', ro.ClockInLocation__c != null?'Latitude:'+ ro.ClockInLocation__c.getLatitude().format() + ';Longitude:' + ro.ClockInLocation__c.getLongitude().format() :'');//上班打卡定位
            data.put('InLocation', ro.InLocation__c);//上班详细地址
            data.put('ClockOutTime', ro.ClockOutTime__c != null?ro.ClockOutTime__c.format(Utils.DATETIME_FORMAT_STR):'');//下班打卡时间
            data.put('ClockOutLocation', ro.ClockOutLocation__c != null?'Latitude:'+ ro.ClockOutLocation__c.getLatitude().format() + ';Longitude:' + ro.ClockOutLocation__c.getLongitude().format() :'');//下班打卡定位
            data.put('OutLocation', ro.OutLocation__c);//下班详细地址
            try {
                data.put('WorkHour', ro.WorkHour__c.format());//工作时长(小时)
            } catch(Exception e) {
                data.put('WorkHour', '');//工作时长(小时)
            }
            data.put('ts', ro.ClockInTime__c.format(Utils.DATETIME_FORMAT_STR));//最后更新时间
            datas.add(data);
            i++;
            if (Math.mod(i,100) == 0) {
                cnt++;
                datasMap.put(String.valueOf(cnt), datas);
                datas = new List<Map<String,String>>();
            }
            
            
        }
       if(datas.size() > 0)datasMap.put(String.valueOf(cnt+1), datas);
        return Utils.getRestReturnMessage(true,'成功查询到记录',maxTs,datasMap);
    }
    
}